<?php

/**
 * LoginForm class.
 * LoginForm is the data structure for keeping
 * user login form data. It is used by the 'login' action of 'SiteController'.
 */
class AdminLogin extends CFormModel
{
	public $zda_username;
	public $zda_password;
	public $rememberMe;
	//定义变量。存放验证码
	public $verifyCode;
	private $_identity;

	/**
	 * Declares the validation rules.
	 * The rules state that username and password are required,
	 * and password needs to be authenticated.
	 */
	public function rules()
	{
		return array(
			// username and password are required
			array('zda_username, zda_password', 'required'),
			array('zda_username', 'exist', 'className'=>'Adminer', 'message'=>'你输入的用户名不存在！'),
			// rememberMe needs to be a boolean
			//array('rememberMe', 'boolean'),
			// password needs to be authenticated
			//array('zda_password', 'authenticate'),
			//验证码验证
			array('verifyCode','captcha'),
			array('zda_username, zda_password', 'safe', 'on'=>'search'),
		);
	}

	/**
	 * Declares attribute labels.
	 */
	public function attributeLabels()
	{
		return array(
			'rememberMe'=>'记住密码',
			'zda_username'=>'用户名',
			'zda_password'=>'密码',
			'verifyCode'=>'验证码',
		);
	}

	/**
	 * Authenticates the password.
	 * This is the 'authenticate' validator as declared in rules().
	 */
	public function authenticate($attribute,$params)
	{
		if(!$this->hasErrors())
		{
			$this->_identity=new UserIdentity($this->zda_username,$this->zda_password);
			if(!$this->_identity->authenticate())
				$this->addError('zm_psword','用户名或者密码错误，请重新输入！');
		}
	}

	/**
	 * 登录方法
	 * */
	public function login()
	{
		if($this->_identity===null)
		{
			$this->_identity=new AdminerIdertity($this->zda_username,$this->zda_password);
			$this->_identity->authenticate();
		}
		if($this->_identity->errorCode===AdminerIdertity::ERROR_NONE)
		{
			$duration=$this->rememberMe ? 3600*24*30 : 0; // 30 days
			Yii::app()->user->login($this->_identity,$duration);
			return true;
		}
	}
}
